package com.xm.myapplication.Util;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jakewharton.rxbinding3.view.RxView;
import com.xm.httpapi.BaseUtils.Base64Util;
import com.xm.httpapi.BaseUtils.RSAUtils;
import com.xm.myapplication.Listener.SingleOnclickListener;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Type;
import java.security.PublicKey;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import io.reactivex.functions.Consumer;


/**
 *
 */

public class Utils {

    public static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ1fHQ8yjevvzsCBOcUinQ1L9wr0EsQdZapu7sS+gXZw4GRhpkmLTtizX1rN1AGkvJOoaokXCVRJZS/GyH+lPM0CAwEAAQ==";

    public static String getMac() {
        String macSerial = "";
        try {
            Process pp = null;
            try {
                pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
            } catch (IOException e) {
                e.printStackTrace();
            }
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            while ((line = input.readLine()) != null) {
                macSerial += line.trim();
            }

            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return macSerial;
    }

    public static Long currentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());
        Long time = (curDate.getTime() / 1000);
        return time;
    }

    public static String randomMath() {
        String strRand = "";
        for (int i = 0; i < 10; i++) {
            strRand += String.valueOf((int) (Math.random() * 10));
        }

        SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        String imgRandom = str + strRand;
        return imgRandom;
    }

//    public static String sortList(ArrayList<NameValuePair> list) {
//        StringBuffer stringBuffer = new StringBuffer();
//        Map<String, String> map = new TreeMap<>();
//        for (NameValuePair name : list) {
//            map.put(name.getName(), name.getValue());
//        }
//        Set<String> setstr = map.keySet();
//        Iterator<String> iter = setstr.iterator();
//        while (iter.hasNext()) {
//            String key = iter.next();
//            String value = map.get(key);
//            stringBuffer.append(value);
//        }
//        String sign = stringBuffer.toString();
//        Log.i("======", "======sign" + sign);
//        return hmac_sha1(sign);
//    }

    public static String sortList(Map<String, String> map) {
        StringBuffer stringBuffer = new StringBuffer();
        Set<String> setstr = map.keySet();
        Iterator<String> iter = setstr.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            String value = map.get(key);
            stringBuffer.append(value);
        }
        String sign = stringBuffer.toString();
        log.e(sign);
        return hmac_sha1(sign);
    }

    public static String hmac_sha1(String datas) {
        String reString = "";
        String key = "a97a646ee6d9b0953357c8bbda61b87d";
        try {
            byte[] data = key.getBytes("UTF-8");
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
            //生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance("HmacSHA1");
            //用给定密钥初始化 Mac 对象
            mac.init(secretKey);

            byte[] text = datas.getBytes("UTF-8");
            //完成 Mac 操作
            byte[] text1 = mac.doFinal(text);

            reString = bytesToHexString(text1);

        } catch (Exception e) {
            // TODO: handle exception
        }

        return reString;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static String getRsaMessage(String password) {
        PublicKey rsaPublicKey = null;
        try {
            rsaPublicKey = RSAUtils.loadPublicKey(Utils.PUBLIC_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] encryptByte = RSAUtils.encryptData(password.getBytes(), rsaPublicKey);
        String passwordRSA = Base64Util.encode(encryptByte);
        return passwordRSA;
    }

//    // Storage Permissions
//    private static final int REQUEST_EXTERNAL_STORAGE = 1;
//    private static String[] PERMISSIONS_STORAGE = {
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * * Checks if the app has permission to write to device storage
     * *
     * * If the app does not has permission then the user will be prompted to
     * * grant permissions
     * *
     * * @param activity
     */
//    public static void verifyStoragePermissions(Context activity1) {
//        // Check if we have write
//        MVPActivity activity = (MVPActivity) activity1;
//        int permission = ActivityCompat.checkSelfPermission(activity,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE);
//
//        if (permission != PackageManager.PERMISSION_GRANTED) {
//            // We don't have permission so prompt the user
//            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
//                    REQUEST_EXTERNAL_STORAGE);
//        }
//    }
    public static boolean isMobileNO(String mobiles) {
        //第一位必定为1，第二位必定为3或4,5或8，其他位置的可以为0-9,必须为11位数

        String telRegex = "[1][3456789]\\d{9}";
        if (TextUtils.isEmpty(mobiles) && telRegex.length() != 11) {
            return false;
        } else {
            return mobiles.matches(telRegex);
        }
    }

    public static boolean isIDCard(String mobiles) {
        String telRegex = "(^\\\\d{15}$)|(^\\\\d{17}([0-9]|X)$)";
        return mobiles.matches(telRegex);
    }

    public static void backgroundAlpha(float bgAlpha, Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 截取全屏
     *
     * @return
     */
    public static Bitmap captureScreenWindow(Activity activity) {
        activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
        Bitmap bmp = activity.getWindow().getDecorView().getDrawingCache();
        return bmp;
    }


    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "kaola");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(file.getPath()))));
    }

    /**
     * 将dip换算为px
     *
     * @param context
     * @param dpValue
     * @return
     */

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            int versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            log.e("Exception:" + e);
        }
        return versionName;
    }

    /**
     * 返回当前程序版本名
     */
    public static int getAppVersionCode(Context context) {
        int versioncode = 0;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versioncode = pi.versionCode;
        } catch (Exception e) {
            log.e("Exception:" + e);
        }
        return versioncode;
    }

    /**
     * 隐藏软键盘
     *
     * @param context
     * @return
     */
    public static void isHideKeyborad(Context context, View view) {
        isHideKeyborad(context, 0, view);
    }

    public static void isHideKeyborad(Context context, int type, View view) {//0为隐藏 1为显示 2为隐藏显示互换
        if (view == null) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        switch (type) {
            case 0:
                if (isOpen)
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                break;
            case 1:
                if (!isOpen)
                    imm.showSoftInputFromInputMethod(view.getWindowToken(), 0);
                break;
            case 2:
                imm.toggleSoftInputFromWindow(view.getWindowToken(), 0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
        }
    }


    public static boolean isForeground(Context context) {
        if (context != null) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
            String currentPackageName = cn.getPackageName();
            if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName())) {
                return true;
            }
            return false;
        }
        return false;
    }

    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }
        return false;
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("([0-9]\\d*\\.?\\d*)|(0\\.\\d*[0-9])");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        //获得assets资源管理器
        AssetManager assetManager = context.getAssets();
        //使用IO流读取json文件内容
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
            arrayList.add(new Gson().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }

    public static String parseDateTime(String dateString, String originalFormat, String outputFromat) {

        SimpleDateFormat formatter = new SimpleDateFormat(originalFormat, Locale.US);
        Date date = null;
        try {
            date = formatter.parse(dateString);

            SimpleDateFormat dateFormat = new SimpleDateFormat(outputFromat, new Locale("US"));

            return dateFormat.format(date);

        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
    }

//    public static Drawable getDrawable(Context context, int drawableResId, int colorFilter) {
//        Drawable drawable = getDrawable(context, drawableResId);
//        drawable.setColorFilter(ContextCompat.getColor(context, colorFilter), PorterDuff.Mode.SRC_IN);
//        return drawable;
//    }

//    public static Drawable getDrawable(Context context, int drawableResId) {
//        return VectorDrawableCompat.create(context.getResources(), drawableResId, context.getTheme());
//    }

    /**
     * 获取今天往后一周的日期(年月日)
     */
    public static List getDate(int dayCount) {
        List dates = new ArrayList();
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        for (int i = 0; i < dayCount; i++) {
            get31Day(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH) + i, 1, dates);
        }
        return dates;
    }

    public static void get31Day(int mYear, int mMonth, int mDay, int count, List dates) {
        if (mMonth == 1 || mMonth == 3 || mMonth == 5 || mMonth == 7 ||
                mMonth == 8 || mMonth == 10 || mMonth == 12) {
            if (mDay > 31) {
                mMonth++;
                mDay -= 31;
                get31Day(mYear, mMonth, mDay, count++, dates);
            }
        } else if (mMonth == 4 || mMonth == 6 || mMonth == 9 || mMonth == 11) {
            if (mDay > 30) {
                mMonth++;
                mDay -= 30;
                get31Day(mYear, mMonth, mDay, count++, dates);
            }
        } else if (mMonth == 2) {
            if (mDay > 28) {
                mMonth++;
                mDay -= 28;
                get31Day(mYear, mMonth, mDay, count++, dates);
            }
        }
        if (mMonth > 12) {
            mYear++;
            mMonth -= 12;
            get31Day(mYear, mMonth, mDay, count++, dates);
        }
        count--;
        if (count == 0) {//最后一层加数据
            if (dates.size() == 0) {
                dates.add(String.valueOf(mYear) + "-" + String.valueOf(mMonth) + "-" + String.valueOf(mDay));
            } else if (dates.size() == 1) {
                dates.add(String.valueOf(mYear) + "-" + String.valueOf(mMonth) + "-" + String.valueOf(mDay));
            } else if (dates.size() == 2) {
                dates.add(String.valueOf(mYear) + "-" + String.valueOf(mMonth) + "-" + String.valueOf(mDay));
            } else {
                dates.add(String.valueOf(mYear) + "-" + String.valueOf(mMonth) + "-" + String.valueOf(mDay));
            }
        }
        return;
    }


    public static String dataOne(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return times;
    }

    public static boolean isIdCard(String str) {
        boolean isVerify = false;
        if (str.length() != 18) {
            return isVerify;
        }
        if (str.length() == 15) {
            Pattern pattern = Pattern.compile("^(\\d{15})$");
            Matcher isIdCardNum = pattern.matcher(str);
            if (!isIdCardNum.matches()) {
                return isVerify;
            }
            return true;
        } else {
            String str_17 = str.substring(0, 17);
            Pattern pattern = Pattern.compile("^(\\d{17})$");
            Matcher isIdCardNum = pattern.matcher(str_17);
            if (!isIdCardNum.matches()) {
                return isVerify;
            }
            String str_18 = str.substring(17, 18);
            Pattern pattern_18 = Pattern.compile("^(\\d{1})$");
            Matcher isIdCardNum_18 = pattern_18.matcher(str_18);
            if (!isIdCardNum_18.matches()) {
                if (!str_18.equals("x") && !str_18.equals("X")) {
                    return isVerify;
                }
            }
        }
        return true;
    }

    /**
     * 设置沉浸式状态栏
     *
     * @param activity
     */

    public static void setImmersiveStatusBar(Activity activity) {

        activity.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }


    public static void backgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp);
    }

    @SuppressLint("CheckResult")
    public static void singleOnclickListener(View view, SingleOnclickListener singleOnclickListener) {
        RxView.clicks(view)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe((Consumer<Object>) o -> {
                    if (singleOnclickListener != null) singleOnclickListener.onclick();
                });
    }


    public static PackageInfo getApkInfo(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            String packageName = appInfo.packageName;  //得到安装包名称
            String versionName = info.versionName;//获取安装包的版本名
            int version = info.versionCode;
            return info;
        }
        return null;
    }


}


